package com.yuaihen.camera

import android.Manifest
import android.content.Intent
import android.graphics.Bitmap
import android.hardware.Camera
import android.net.Uri
import android.os.Bundle
import android.view.ViewTreeObserver
import android.view.WindowManager
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.yuaihen.camera.utils.FileUtils
import kotlinx.android.synthetic.main.activity_camera_preview.*
import java.io.File
import java.io.FileOutputStream

/**
 * Created by Yuaihen.
 * on 2020/7/17
 */
class CameraPreviewActivity : BaseActivity(), ViewTreeObserver.OnGlobalLayoutListener {

    //    private var cameraHelper: CameraHelper? = null
    private var previewSize: Camera.Size? = null

    companion object {
        const val TAG = "CameraPreviewActivity"
    }

    /**
     * 所需的所有权限信息
     */
    private val NEEDED_PERMISSIONS = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        window.attributes.screenBrightness = 1f
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera_preview)

        initListener()
    }

    private fun initListener() {
        cameraView.viewTreeObserver.addOnGlobalLayoutListener(this)
        btn_start_preview.setOnClickListener {
            cameraView.cameraHelper?.openCamera()
            cameraView.cameraHelper?.startPreview(cameraView.surfaceTexture)

        }

        btn_pause_preview.setOnClickListener {
            cameraView.cameraHelper?.stop()
//            cameraHelper
        }

        iv_takePhoto.setOnClickListener {
            takePhoto()
        }

        iv_switchCamera.setOnClickListener {
            cameraView.switchCamera()
        }
    }


    private fun takePhoto() {
        cameraView.takePicture { bitmap ->
            val file: File = FileUtils.createImageFile()
            //重新写入文件
            try {
                // 写入文件File
                val fos = FileOutputStream(file)
                //默认jpg
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.flush()
                fos.close()
                bitmap.recycle()
                sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(file)))
                Toast.makeText(this, "照片已保存", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onDestroy() {
//        cameraHelper?.let {
//            it.release()
//            cameraHelper = null
//        }
        super.onDestroy()
    }

    private val ACTION_REQUEST_PERMISSIONS = 0X001

    /**
     * 在textureView第一次布局完成后,去除该监听 并且进行引擎和相机的初始化
     */
    override fun onGlobalLayout() {
        cameraView.viewTreeObserver.removeOnGlobalLayoutListener(this)
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS)
        } else {
//            initEngine()
            initCamera()
        }
    }

    private fun initCamera() {
        cameraView.enableBeauty(true)

//        val cameraListener = object : CameraListener {
//            override fun onCameraOpened(camera: Camera, cameraId: Int, displayOrientation: Int, isMirror: Boolean) {
//                Log.i(TAG, "onCameraOpened: $cameraId  $displayOrientation $isMirror")
//                previewSize = camera.parameters.previewSize
//            }
//
//            override fun onPreview(data: ByteArray?, camera: Camera?) {
//                Log.i(TAG, "onPreview: ")
//            }
//
//            override fun onCameraClosed() {
//                Log.i(TAG, "onCameraClosed: ")
//            }
//
//            override fun onCameraConfigurationChanged(cameraID: Int, displayOrientation: Int) {
//                Log.i(TAG, "onCameraConfigurationChanged: $cameraID   $displayOrientation")
//            }
//
//            override fun onCameraError(e: Exception?) {
//                Log.i(TAG, "onCameraError: " + e?.message)
//            }
//        }
//
//        cameraHelper = CameraHelper.Builder()
//                .previewViewSize(Point(texture_preview.measuredWidth, texture_preview.measuredHeight))
//                .rotation(windowManager.defaultDisplay.rotation)
//                .isMirror(false)
//                .previewOn(texture_preview)
////                .previewSize(Point(1080, 1920))
//                .cameraListener(cameraListener)
//                .build()
//        cameraHelper?.let {
//            it.initPreviewCallback()
//            it.openCamera()
//        }

    }


    override fun afterRequestPermission(requestCode: Int, isAllGranted: Boolean) {
        if (requestCode == ACTION_REQUEST_PERMISSIONS) {
            if (isAllGranted) {
//                initEngine()
                initCamera()
            } else {
                showToast("权限被拒绝！")
            }
        }
    }

}